;$(function() {
	var serverIdArr='';
	var id = $("#id").val();
	if(id==null||id==''){
		upload(serverIdArr);
		getVisitUserList("kk",null);
    }else{
    	getInfo(id,serverIdArr);	
    }
	submitForm();
 })
 var tale = new $.tale();//弹框
function upload(serverIdArr){
    $("#dropzone").dropzone({
        paramName: "file",
        url: ctxPath+"/file/upload",
        addRemoveLinks: true,
        dictRemoveLinks: "x",
//        uploadMultiple: true,
        maxFilesize: 10,
        init: function () {
            this.on("success", function (file, msg) {
               	file.serverId=msg.message;
               	serverIdArr=msg.message;
            	$("#image_files").val(serverIdArr);
            });
            this.on('error', function (files, response) {
                //文件上传失败后的操作
            	console.log(files, response);
            });
            //删除图片的事件，当上传的图片为空时，使上传按钮不可用状态
            this.on("removedfile", function (file) {
            	$("#image_files").val("");
            });
        }
    });
}

function getInfo(id,serverIdArr){
	    if(id==null||id==''){
	    	return;
	    }
	   $.ajax({
        url: ctxPath+"/visit/letter/findById/"+id,
        type: 'GET',
        success: function(d){
        	var success = d.success;
        	 if(success==true){
        	 var data=  d.data;
        	 umbinding.bind(data);
        	 toHtml(data);
        	 ue.ready(function(){//监听编辑器实例化完成的事件
     			ue.setContent(data.content);
        	 });
        	 serverIdArr=data.fileId;
        	 getVisitUserList(null,data.userId);
        	 $("#image_files").val(serverIdArr);
        	 var myDropzone = new Dropzone("#dropzone", {
        	        paramName: "file",
        	        url: "/file/upload",
        	        addRemoveLinks: true,
        	        dictRemoveLinks: "x",
//        	        uploadMultiple: true,
        	        maxFiles: 3,
        	        maxFilesize: 10,
        	        init: function () {
        	            this.on("success", function (file, msg) {
        	               	file.serverId=msg.message;
        	               	serverIdArr=msg.message;
        	            	$("#image_files").val(serverIdArr);
        	            });
        	            this.on('error', function (files, response) {
        	            });
        	            //删除图片的事件，当上传的图片为空时，使上传按钮不可用状态
        	            this.on("removedfile", function (file) {
        	            	$("#image_files").val("");
        	            });
        	        }
        	    });
        	 if(data.files!=null){
        	  for (var i = 0; i < data.files.length; i++) {
        		   var size = data.files[i].size*1024;
        			 var mockFile = { 
        					 name: data.files[i].srcname,
        					 accepted:true,
        					 size: size, //图片尺寸
    					     height:"70%",
    					     width:"70%",
    					     type:'.jpg,.png,.gif'//图片文件类型
        					    };
                	 myDropzone.emit("addedfile", mockFile);
                	 myDropzone.emit("thumbnail", mockFile, ctxPath+"/file/showImage/"+data.files[i].id);
                	 myDropzone.emit("complete", mockFile);	
                	 myDropzone.options.maxFiles = myDropzone.options.maxFiles - 1;
				} 
        	 }
        	}
        }
    });
}


function submitForm(){
	$("#global-form").validator({
		rules: {
			mobile: function(element, params) {
				var tel =/^(0|86|17951)?(13[0-9]|15[012356789]|17[012356789]|18[0-9]|14[57])[0-9]{8}$/;
			    return tel.test(element.value) || '请检查电话号码';
			},mobileAjax: function(element, params) {
				  $.ajax({
				    	url: ctxPath+'/user/cheakPhone',
				        type: 'POST',
				        data: json,
				        success: function(d){
				        	var success = d.success;
				        }
				    });
			    return tel.test(element.value) || '请检查电话号码';
			},select_check: function(element, params) {
				var isInvalid = false;
				if(element.value =-1){
					isInvalid=true;
				}
			    return isInvalid||'请选择！';
			},isCardCheck: function(element, params) {
				var isInvalid = false;
				var card =/(^\d{15}$)|(^\d{17}([0-9]|X)$)/;
				return card.test(element.value) || '请检查身份证';
			}
		},
	    fields: {
	    	'title':{
				rule : "required;",
				msg : {
					required : "必填!"
				}
			},
			'userId':{
				rule : "required;",
				msg : {
					required : "必填!"
				}
			},
	    },
	    invalid: function(form, errors){
	    	console.log(errors);
	    	$(".btn-submit").removeAttr("style");
	    },
	    //验证成功
	    valid: function(form) {
	    	 saveInfo();
	    },
	});
}

function toHtml(data){
	
}

function saveInfo(){
	var json =$("#global-form").serializeFormJSON();
	console.log(json);
	var id = $("#id").val();
	var url= ctxPath+"/visit/letter/saveInfo";
	if(id!=''&&id!=null){
		url = ctxPath+"/visit/letter/updateInfo";
	}
    $.ajax({
    	url: url,
        type: 'POST',
        data: json,
        success: function(d){
        	var success = d.success;
        	if(success){
        	tale.alertOk({
                       text:'保存成功',
                       then: function () {
                           setTimeout(function () {
                               window.location.href = ctxPath+'/visit/letter/list';
                           }, 500);
                       }
                   });
        	}else{
        		tale.alertError(d.message || '保存失败');
        	}
        }
    });
}

/**
 * 查询信访人
 * @returns
 */
function getVisitUserList(remark,userId){
	console.log(remark);
	var userList = [];
	 userList.push('<option>-请选择-</option>');
	$.ajax({
		url: ctxPath+"/visit/letter/getVisitUserList",
		type: 'POST',
		data: {remark:remark},
		success: function(d){
			var success = d.success;
			if(success){
			$.each(d.data,function(i,item){
				var opt = '<option value="'+item.userId+'" >'+item.name+'-'+item.phone+'</option>';
				if(item.userId==userId){
				     opt = '<option value="'+item.userId+'" selected>'+item.name+'-'+item.phone+'</option>';
				}
				userList.push(opt);
			})
			}
			$("#user_id").html(userList);
			 //1 执行完毕后去掉之前生成的div
//			  $('#user_id').searchableSelect();
			  $('#user_id').trigger('change');
		}
	});
}
